package hn.cch.framework.http;

import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OkHttpUtil {

    public static OkHttpClient initHttp() {
        Builder builder = new Builder();
        HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
        builder.cookieJar(new CookieJar() {

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }

        });
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    }

    public static String sentHttp(OkHttpClient okHttpClient, Request request) {
        try {
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            String body = response.body().string();
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送
     * @param okHttpClient
     * @return
     */
    public static String sentGet(OkHttpClient okHttpClient) {

        HttpUrl httpUrl = new HttpUrl.Builder()
                .host("http://127.0.0.1:8080")
                .addPathSegments("/path1/path2")
                .addQueryParameter("key", "value")
                .build();
        Request request = new Request.Builder().url(httpUrl).get().build();

        return sentHttp(okHttpClient, request);
    }

    /**
     * 根据json方式发送post请求
     * @param okHttpClient
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public static String sentPost(OkHttpClient okHttpClient, String url, String data) throws Exception {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return sentHttp(okHttpClient, request);
    }

    /**
     * 根据form方式发送post请求
     * @param okHttpClient
     * @param url
     * @return
     */
    public static String sentForm(OkHttpClient okHttpClient, String url) {
        RequestBody requestBody = new FormBody.Builder()
                .add("key", "value")
                .build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return sentHttp(okHttpClient, request);
    }


    /**
     * 解析url
     * @param url
     * @param name
     * @return
     */
    public static String parseUrl(String url,String name){
        HttpUrl httpUrl = HttpUrl.parse(url);
        String value = httpUrl.queryParameter(name);
        return value;
    }

    /**
     * 正则表达式解析html
     * @param regExp
     * @param htmlText
     * @return
     */
    public static String parseHtml(String regExp, String htmlText) {

        String result = null;
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(htmlText);
        if (matcher.find()) {
            result = matcher.group();
        }
        return result;
    }

    /**
     * 解析url
     * @param url
     * @return
     */
    public static Map<String, String> parseUrl(String url) {
        String params = url.substring(url.indexOf("?") + 1);
        Map<String, String> map = new HashMap<>();
        try {
            for (String param : params.split("&")) {
                String[] kv = param.split("=");
                if (kv.length != 2) {
                    continue;
                }
                String key = kv[0];
                String value = URLDecoder.decode(kv[1], "utf-8");
                map.put(key, value);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }


}

